package cn.com.captureNetPacket.iatConfigImpl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PreDestroy;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import com.iflytek.mt_scylla.mt_scylla;

import cn.com.captureNetPacket.iatConfig.IatConfig;
import cn.com.captureNetPacket.model.SignallingInfo;
import cn.com.captureNetPacket.util.JsonPathUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@ConditionalOnProperty(name = "cnp.iat.enable", havingValue = "true",matchIfMissing = false)
public class IflytekConfig implements IatConfig {
		@Value("${cnp.iat.connectUrl}")
		private   String iflytekConnectString;
 
		private static  mt_scylla mt;
		private static int lockCount=0;
		 
//		public static void initIatConfig(String iflytekConnect){
//			iflytekConnectString=iflytekConnect;
//		}
		
		
		
			/**
			* <strong>Title: <strong>
			* <p>Description: <p>
			* <p>Company: </p> 
			*<strong>Copyright:</strong> Copyright (c) 2019
			* @version: 1.0
			* @author  ASUS:augustWei
			* @date  2021 下午3:58:38
			* @return
			* @see cn.com.captureNetPacket.iatConfig.IatConfig#getScylla()
			*/
		public  mt_scylla  getScylla() {
			if(mt==null)
			{
			mt = new mt_scylla();
			// 初始化语音识别引擎
			int initret = mt.SCYMTInitializeEx(null);
			String parL = "appid=pc20onli,sn=c" + ",url="+ iflytekConnectString;
			log.debug("getScylla  初始化参数: {}",parL) ;
			mt.SCYMTAuthLogin(parL, null);
			if(initret != 0){
			     log.error("getScylla 请检查IP地址是否正确、网络是否正常开启,错误码是 : {}" , initret);
//			     System.exit(0);
			}
			} 
		return mt;
		}
		
		
			/**
			* <strong>Title: <strong>
			* <p>Description: <p>
			* <p>Company: </p> 
			*<strong>Copyright:</strong> Copyright (c) 2019
			* @version: 1.0
			* @author  ASUS:augustWei
			* @date  2021 下午3:58:38
			* @param rate
			* @return
			* @see cn.com.captureNetPacket.iatConfig.IatConfig#iatOnlineBegin(int)
			*/
		@Override
		public String iatOnlineBegin(int rate,SignallingInfo signallingInfo) {
			getScylla();
			String  session_id=null;
			String ssbparam = "svc=iat,auf=audio/L8;rate="+8000+",aue=alaw,type=1,uid=660Y5r,appid=pc20onli,url=" + iflytekConnectString;
//			String ssbparam = "svc=iat,auf=audio/L16;rate="+rate+",aue=speex,type=1,uid=660Y5r,appid=pc20onli,url=" + iflytekConnectString;
//			String ssbparam = "svc=iat,auf=audio/L16;rate="+rate+",aue=speex-wb,type=1,uid=660Y5r,appid=pc20onli,url=" + iflytekConnectString;
//			String ssbparam = "svc=iat,auf=audio/L16;rate="+rate+",aue=raw,type=1,uid=660Y5r,appid=pc20onli,url=" + iflytekConnectString;
//			String ssbparam = "svc=iat,auf=audio/L16;rate="+rate+",aue=raw,type=1,uid=660Y5r,appid=pc20onli,url=" + iflytekConnectString;
			int[] errorCode = new int[1];  
			try {
			log.debug("iatOnlineBegin  初始化参数  : {}",ssbparam) ;
			   session_id = mt.SCYMTSessionBeginEx(ssbparam, errorCode,null);
			if(errorCode[0] != 0){
				 log.error("iatOnlineBegin 请检查IP地址是否正确、网络是否正常开启,错误码是 : {}" , errorCode[0]);
				   return null;
				    // System.exit(0);
				}
			
			}catch (Exception e) {
				log.error("iatOnlineBegin session_id: {}",session_id);
			}
			synchronized (mt) {
				lockCount++;
			}
			log.debug("beginSession  : {} 在线识别会话已开始。",session_id);
			  return session_id;
		}
		
		
		
			/**
			* <strong>Title: <strong>
			* <p>Description: <p>
			* <p>Company: </p> 
			*<strong>Copyright:</strong> Copyright (c) 2019
			* @version: 1.0
			* @author  ASUS:augustWei
			* @date  2021 下午3:58:38
			* @param session_id
			* @param buffer
			* @param audioStatus
			* @return
			* @see cn.com.captureNetPacket.iatConfig.IatConfig#iatOnlineWrite(java.lang.String, byte[], int)
			*/
		@Override
		public Map<String, Object> iatOnlineWrite(String session_id,byte[] buffer,int audioStatus,SignallingInfo signallingInfo) {
			 int[] ret = new int[1]; 
			 int[] epStatus = new int[1];
	         int[] recogStatus = new int[1];  
	         Map<String, Object> product=null;
	         try {
			  //写入音频	    
        	String cur_res = mt.SCYMTAudioWriteEx(session_id, buffer, buffer.length, audioStatus, epStatus, recogStatus, ret, null);	        		    
//        	log.debug(" iatOnlineWrite ---------------||||||||||||||||||||>>>>>>>>>推送到科大  session_id : {} 大小: {}  audioStatus: {}  ",session_id,buffer.length,audioStatus);
            if (ret[0] != 0) { 		         
            	 log.error("iatOnlineWrite 上传音频出错，session_id: {} 错误码为 : {}" , session_id,ret[0]);
            	//System.exit(0);  		    
            }   		
           product=new HashMap<String, Object>();
            // 判断引擎返回pgs是否为1，为1表示有识别结果可获取 		        			
            if (ret[0] == 0 && cur_res.length() != 0){  	
            	log.debug("---------:{}",cur_res);
            	//解析json
            	  product =JsonPathUtil.getValue(cur_res, "$",Map.class);
        		//输出                	
            	if(product.get("pgs").toString().equals("1"))
            	{
//                	log.debug(" iatOnlineWrite --------------------------------->>>>>>>\r\n识别到的结果为: {}",product.get("result"));
                	return product;
            	}else 
            		log.info("iatOnlineWrite ，session_id: {} 未识别到结果: {}",session_id,cur_res);

            	//break;      //是否连续识别
            } 
            
	         }catch (Exception e) {
				log.error("iatOnlineWrite session_id: {}",session_id,e);
			}
			return product;
		}
		
		
		
		
		
			/**
			* <strong>Title: <strong>
			* <p>Description: <p>
			* <p>Company: </p> 
			*<strong>Copyright:</strong> Copyright (c) 2019
			* @version: 1.0
			* @author  ASUS:augustWei
			* @date  2021 下午3:58:38
			* @param ssbparam
			* @return
			* @see cn.com.captureNetPacket.iatConfig.IatConfig#iatOffline(java.lang.String)
			*/
		@Override
		public String iatOffline(String ssbparam,SignallingInfo signallingInfo) {
			//离线识别
			ssbparam = "svc=iat,auf=audio/L16;rate=8000,aue=raw,type=1,uid=660Y5r,appid=pc20onli,url=" + iflytekConnectString +"," +"extend_params={\"params\":\"seginfo=1,vspp=1,online=off\"}";
			return null;
		}
			/**
			* <strong>Title: <strong>
			* <p>Description: <p>
			* <p>Company: </p> 
			*<strong>Copyright:</strong> Copyright (c) 2019
			* @version: 1.0
			* @author  ASUS:augustWei
			* @date  2021 下午3:58:38
			* @param ssbparam
			* @return
			* @see cn.com.captureNetPacket.iatConfig.IatConfig#iatTranslate(java.lang.String)
			*/
		@Override
		public String iatTranslate(String ssbparam,SignallingInfo signallingInfo) {
			//识别后翻译
			ssbparam = "url=" + iflytekConnectString + ",svc=src,appid=pc20onli,scenes=iat;itr,scenes_params={\"iat\":\"svc=iat,auf=audio/L16;rate=16000,aue=raw,type=1,uid=660Y5r\"|\"itr\":\"type=cnug\"}";

			return null;
		}
		
			/**
			* <strong>Title: <strong>
			* <p>Description: <p>
			* <p>Company: </p> 
			*<strong>Copyright:</strong> Copyright (c) 2019
			* @version: 1.0
			* @author  ASUS:augustWei
			* @date  2021 下午3:58:38
			* @param session_id
			* @see cn.com.captureNetPacket.iatConfig.IatConfig#endSession(java.lang.String)
			*/
		@Override
		public  void endSession(String session_id,SignallingInfo signallingInfo) {
			if(mt==null)return ;
			synchronized (mt) {
			lockCount--;
			}
			
			// 结束一路会话
			int endret = mt.SCYMTSessionEndEx(session_id);
			if(endret != 0){
			    log.error("endSession session_id： {}会话关闭失败,错误码是 : {}" ,session_id, endret);
			  //  System.exit(0);
			}
			log.debug("endSession  : {} 会话已结束。",session_id);
			
			
			try {
				if(mt!=null)
				mt.wait(300000);
			} catch (InterruptedException e) {
				 log.warn("endSession ",e);
			}
			
			if(lockCount<1)
				destory();
			
		}
		
		 
			/**
			* <strong>Title: <strong>
			* <p>Description: <p>
			* <p>Company: </p> 
			*<strong>Copyright:</strong> Copyright (c) 2019
			* @version: 1.0
			* @author  ASUS:augustWei
			* @date  2021 下午3:58:38
			* @see cn.com.captureNetPacket.iatConfig.IatConfig#destory()
			*/
		@Override
		@PreDestroy
		public  void destory() {
			if(mt!=null) {
			try {
					// 逆初始化
						int uniret = mt.SCYMTUninitializeEx(null);
						if(uniret != 0){
						    log.error(" destory  SCYMTUninitializeEx  逆初始化失败,错误码是 : {}",uniret);
						  //  System.exit(0);
						}
			}catch (Exception e) {
				 log.error("SCYMTUninitializeEx Exception : {}",e);
			}finally {
				mt=null;
			}
					 
			log.debug("destory 正在结束资源");
			}
		}


			@Override
			public void initIatConfig() {
				log.debug("initIatConfig ----------->>>>>>>>>>>iflytekConnectString: {} ",iflytekConnectString);
			}

 
   }
